'use strict';
// 查询趣事分享列表
const db = uniCloud.database();
exports.main = async (event, context) => {

	// 查询条件
	let parmse = {};

	let res = null;
	if (event.state == 'add') {
		parmse = event
		delete parmse['state'] //删除这个多余的状态
		res = await db.collection('footprint').add(parmse);
		return {
			code: 200,
			message: "操作成功"
		}
	} else if (event.state == 'update') {
		parmse = event
		let _id = event._id
		delete parmse['state'] //删除这个多余的状态
		delete parmse['_id'] //删除这个多余的状态
		res = await db.collection('footprint').where({
			_id: _id
		}).update(parmse)

		return {
			code: 200,
			message: "操作成功---------"
		}
	} else if (event.state == 'look') {
		parmse = event
		delete parmse['state']



		// 获取朋友圈数据
		res = await db.collection('footprint').where(db.command.or({
			...parmse
		})).orderBy('createTime', 'desc').get() //获取数据


		// res.data.forEach(item => {
		// 	// 获取用户信息
		// 	userList.data.forEach(row => {
		// 		if(item.userId == row._id){
		// 			let itemId = item._id
		// 			Object.assign(item , row)
		// 			item._id = itemId
		// 		}
		// 	})
		// })
		let array = []
		for (let i = 0; i < res.data.length; i++) {
			let item = res.data[i]
			// 获取用户信息
			let userInfo = await db.collection('userList').where({
				_id: item.userId
			}).get()

			// 合并数据
			let itemId = item._id

			if (Array.isArray(userInfo.data) && userInfo.data.length != 0) {
				Object.assign(item, userInfo.data[0])
				if (Array.isArray(item.goodList)) {
					for (let k = 0; k < item.goodList.length; k++) {
						let row = item.goodList[k]
						let userInfoRow = await db.collection('userList').where({
							_id: row._id
						}).get()
						if (userInfoRow.data.length != 0) {
							Object.assign(row, userInfoRow.data[0])
						} else {
							// 删除当前点赞
							item.goodList.splice(k , 1)
							
							let newObj = item
							delete newObj["_id"]
							// 更新数据
							await db.collection('footprint').where({
								_id: itemId
							}).update(newObj)
						}
					}
				}
				item._id = itemId
				array.push(item)
			} else {
				// 如果当前数据未匹配道用户 就删除当前数据
				await db.collection('footprint').doc(item._id).remove()
			}

		}

		return {
			code: 200,
			message: "操作成功",
			data: array,
			total: res.affectedDocs
		}
	} else if (event.state == 'delete') {
		parmse = event


		delete parmse['state']

		console.log(parmse._id, 'parmse');

		let res = await db.collection('footprint').doc(parmse._id).remove()

		return {
			code: 200,
			message: "操作成功"
		}
	}

}